package com.shopoo.oauth.infrastructure.repository;

import javax.annotation.Resource;

import com.shopoo.oauth.domain.constants.BloomFilterConstants;
import com.shopoo.oauth.domain.repository.BloomFilterRepository;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;

/**
 * 用户名布隆过滤器
 * @Author <a href="mailto:android_li@sina.cn">MaoYuan.Li</a>
 * @Date 2022/3/19 4:28 PM
 */
@Repository("usernameBloomFilter")
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) //设置为单例，防止并发引起错误
public class UsernameBloomFilterRepositoryImpl implements BloomFilterRepository, InitializingBean {

	@Resource
	private RedissonClient redissonClient;

	private RBloomFilter bloomFilter;

	@Override
	public boolean add(Object data) {
		return bloomFilter.add(data);
	}

	@Override
	public boolean mightContains(Object data) {
		return bloomFilter.contains(data);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		bloomFilter = redissonClient.getBloomFilter(BloomFilterConstants.BLOOM_FILTER_USERNAME);
		bloomFilter.tryInit(10_10000, 0.001);
	}
}
